import React, { PureComponent } from 'react';
import { Drawer, Button } from 'antd';
import { Editor } from 'react-draft-wysiwyg';
import draftToHtml from 'draftjs-to-html';
import '../../node_modules/react-draft-wysiwyg/dist/react-draft-wysiwyg.css';
import { EditorState, convertToRaw, ContentState } from 'draft-js';
import htmlToDraft from 'html-to-draftjs';
import { connect } from 'dva';
import PropTypes from 'prop-types';

@connect(({ global }) => ({
  global,
}))
class EditorComponent extends PureComponent {
  constructor(props) {
    super(props);

    let context = props.context;
    const contentBlock = htmlToDraft(context ? context : '');
    if (contentBlock) {
      const contentState = ContentState.createFromBlockArray(contentBlock.contentBlocks);
      const editorState = EditorState.createWithContent(contentState);
      this.state = {
        editorState: editorState
      };
    }
  }

  componentWillReceiveProps(nextProps) {
    let context = nextProps.context;
    const contentBlock = htmlToDraft(context ? context : '');
    if (contentBlock) {
      const contentState = ContentState.createFromBlockArray(contentBlock.contentBlocks);
      const editorState = EditorState.createWithContent(contentState);
      this.setState({
        editorState,
      });
    }
  }

  onEditorStateChange = (editorState) => {
    const { dispatch } = this.props;
    // let text = draftToHtml(convertToRaw(editorState.getCurrentContent()));
    let text = draftToHtml(convertToRaw(editorState.getCurrentContent()));
    // this.props.editerSubmit(text);

    this.setState({
      editorState: editorState,
    });
    localStorage.setItem('editerInfo', text);
    // dispatch({
    //   type: 'global/editers',
    //   payload: text,
    // });
  };

  render() {
    const { editorState } = this.state;
    return <Editor
      editorState={editorState}
      onEditorStateChange={this.onEditorStateChange.bind(this)}
    />;
  }
}

EditorComponent.PropTypes = {
  context: PropTypes.string.isRequired,
};

export default EditorComponent;
